/*
Copyright 2014 Yury Kharlamov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated Inversion-Of-Control container
https://code.google.com/p/gen-ioc/

* * *

Object common interfaces and helpers
*/
#pragma once
#include "TypeInfoWrapper.h"

struct IObject
{
	virtual ~IObject(){}
};

typedef std::function <std::shared_ptr<IObject>()> Factory;

struct IEventQueue : public IObject
{
	virtual void PushEvent(const boost::any& event) = 0;
};

struct ISubscriber : public IObject
{
	virtual void SetSelfEventQueue(const std::weak_ptr<IEventQueue>& self) = 0;
};

typedef std::weak_ptr<IEventQueue> Subscriber;
typedef std::list<Subscriber> SubscrList;

struct IEventSource : public IObject
{
	virtual void Subscribe(const std::weak_ptr<IEventQueue>& evtQueue) = 0;
};

struct ISetters : public IObject
{
public:
	virtual void SetIfaceFactory(const IfaceId& ifaceId, const Factory& factory) = 0;
};

struct IShutdown : public IObject
{
	virtual void Shutdown() = 0;
};

struct ShutdownFinished
{
	ShutdownFinished(IShutdown* object) : object(object){}
	IShutdown* object;
};

template<class T>
class LazyPtr
{
public:
	void Set(const Factory& f)
	{
		m_f = f;
	}

	T* operator ->()
	{
		return get();
	}
	T* get()
	{
		if (!m_ptr)
		{
			boost::lock_guard<boost::mutex> lock(m_mutex);
			if (!m_ptr)
			{
				m_ptr = std::dynamic_pointer_cast<T>(m_f());
			}
		}
		return m_ptr.get();
	}
	void instantiate()
	{
		get();
	}
private:

	Factory m_f;
	std::shared_ptr<T> m_ptr;
	boost::mutex m_mutex;
};

template<class T, class Unique>
class private_ptr
{
public:
	private_ptr(){}
	private_ptr(const std::shared_ptr<T>& p)
		:m_ptr(p){}
	T* operator ->()
	{
		return m_ptr.get();
	}
	T* get()
	{
		return m_ptr.get();
	}
	void reset(){ m_ptr.reset(); }
	void swap(private_ptr& ptr){ m_ptr.swap(ptr.m_ptr); }
private:
	std::shared_ptr<T> m_ptr;
};

template <class BaseClass>
std::shared_ptr<IObject> CreateObject();